<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree :tree-data="treeData" v-on:appTreeClick="appTreeClick"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              中心名称：<el-input placeholder="请输入内容" v-model="selectForm.centerName" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              负责人：<el-input placeholder="请输入内容" v-model="selectForm.centerCharge" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              中心层级：
              <el-select v-model="selectForm.centerLevel" clearable placeholder="请选择">
                <el-option v-for="(item,index) in orgLevelOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              是否24小时有人值守：
              <el-select v-model="selectForm.hasOnDuty" clearable placeholder="请选择">
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows">
          </app-table>
          <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" class="custom-dialog_style_twoLine" :before-close="cancel" :close-on-click-modal="false">
            <el-form :model="formData" :rules="rules" ref="formData" :disabled="showOnly" label-width="50%">
              <el-form-item label="中心名称：" prop="centerName" label-width="30%">
                <el-input v-model="formData.centerName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="中心联系方式：" prop="centerPhone" label-width="30%">
                <el-input v-model="formData.centerPhone" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="中心层级：" prop="centerLevel" label-width="30%">
                <el-select v-model="formData.centerLevel" clearable placeholder="请选择">
                  <el-option v-for="(item,index) in orgLevelOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="中心负责人姓名：" prop="centerCharge" label-width="30%">
                <el-input v-model="formData.centerCharge" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="行政区：" prop="regionIdArr">
                <div class="block">
                  <el-cascader
                    placeholder="请选择"
                    :options="regionOptions"
                    filterable
                    clearable
                    :props="areaProps"
                    v-model="formData.regionIdArr"
                    change-on-select>
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="专职工作人员人数：" label-width="30%">
                <el-input v-model="formData.personnelNumber" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="办公用房面积(平方米)：" label-width="30%">
                <el-input v-model="formData.officeSpace" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="年度运行经费(元)：" label-width="30%">
                <el-input v-model="formData.annualOutlay" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="联网公共安全视频监控摄像机数量：" label-width="30%">
                <el-input v-model="formData.videoCameraNumber" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="是否24小时有人值守：" label-width="30%">
                <el-select v-model="formData.hasOnDuty" clearable placeholder="请选择">
                  <el-option label="否" :value="0"></el-option>
                  <el-option label="是" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="所在地：" label-width="30%">
                <el-input v-model="formData.address" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="所在地祥址：" label-width="30%">
                <el-input v-model="formData.addressDetail" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="选择经纬度：" class="custom-longla-container" style="margin-top:0;">
                <el-input v-model="formData.longitude" :disabled="true" placeholder="经度" ></el-input>
                <el-input v-model="formData.latitude" :disabled="true" placeholder="纬度" ></el-input>
                <el-button type="text" @click="openSimpleMap" style="color: red;">[ 选择 ]</el-button>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="isfooterBtnShow">
              <el-button @click="cancel('formData')">取 消</el-button>
              <el-button type="primary" @click="save('formData')">确 定</el-button>
            </div>
          </el-dialog>
          <el-dialog class="dialog-body-mini" :visible.sync="showMap" title="选择经纬度" width="70%" top="8vh" :before-close="mapCancel">
            <edit-map v-if="showMap" :mode="mapMode" @appMapCallback="appMapCallback" :target="mapTarget" ></edit-map>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import EditMap from '@/components/EditMap'
import {getAllRegion} from '@/utils/region'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {getRegionTree, createMapLocation} from '@/http/AppApi'
import {findCenterVideo, createCenterVideo, updateCenterVideo, delCenterVideo} from '@/http/OrgApi'
export default {
  data () {
    return {
      dialogFormVisible: false,
      isfooterBtnShow: true,
      mapHackReset: false,
      showMap: false,
      mapMode: 'simple',
      mapTarget: {},
      pageData: {},
      treeData: [],
      dialogTitle: '',
      currentSelectedData: [],
      showOnly: false,
      tableColumns: [
        { prop: 'centerName', label: '中心名称' },
        { prop: 'centerLevel', label: '中心层级', formatter: this.orgLevelFormatter },
        { prop: 'centerCharge', label: '负责人' },
        { prop: 'address', label: '地址' },
        { prop: 'officeSpace', label: '面积' }
      ],
      tableDada: [],
      regionOptions: [],
      formData: {},
      selectForm: {},
      areaProps: {
        label: 'name',
        value: 'id'
      },
      rules: {
        centerName: [
          { required: true, message: '请输入中心名称', trigger: 'blur' }
        ],
        centerPhone: [
          { required: true, message: '请输入中心联系方式', trigger: 'blur' }
        ],
        centerLevel: [
          { required: true, message: '请选择中心层级', trigger: 'blur' }
        ],
        centerCharge: [
          { required: true, message: '请输入负责人姓名', trigger: 'blur' }
        ],
        regionIdArr: [
          { required: true, message: '请选择行政区', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '请选择经纬度', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '请选择经纬度', trigger: 'blur' }
        ]
      },
      level: 1,
      orgLevelOption: []
    }
  },
  components: {
    EditMap,
    AppTree,
    BtnGroup,
    AppTable
  },
  mounted () {
    this.orgLevelOption = getDictDataOption('层级')
    getRegionTree().then(resp => {
      if (resp.code && resp.code === '200') {
        this.treeData = resp.data
        this.regionOptions = resp.data
      }
    })
    this.getTableData()
  },
  methods: {
    // 格式化层级
    orgLevelFormatter (row, column) {
      let centerLevelOption = getDictDataOption('层级')
      let resGenterLevel = ''
      for (let i = 0; i < centerLevelOption.length; i++) {
        if (centerLevelOption[i].code === row.centerLevel) {
          resGenterLevel = centerLevelOption[i].name
          break
        }
      }
      return resGenterLevel
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$alert('请填写正确表单格式', '', {
            confirmButtonText: '确定'
          })
          return ''
        } else {
          if (this.formData.regionIdArr && this.formData.regionIdArr.length > 0) {
            let len = this.formData.regionIdArr.length - 1
            let regionData = {}
            regionData.id = this.formData.regionIdArr[len]
            regionData.items = this.treeData
            regionData.isGetLevel = true
            let level = getAllRegion(regionData)
            if (this.formData.centerLevel !== level) {
              this.$alert('组织层级与区域不符合', '', {
                confirmButtonText: '确定'
              })
              return ''
            }
            regionData.isGetLevel = false
            regionData.isGetGridCode = true
            // this.formData.allRegionId = getAllRegion(regionData)
            this.formData.allRegionId = this.formData.regionIdArr.join(',')
          }
          if (this.formData.id) {
            updateCenterVideo(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.getTableData()
              }
            })
          } else {
            createCenterVideo(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.getTableData()
              }
            })
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            delCenterVideo(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.getTableData()
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel (formName) {
      this.dialogFormVisible = false
      this.formData = {}
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    },
    getTableData (param) {
      findCenterVideo(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.pageData = resp.data
          if (this.pageData.items && this.pageData.items instanceof Array) {
            this.tableData = this.pageData.items
          }
        }
      })
    },
    handleCurrentChange (val) {
      this.selectForm.offset = (val - 1) * 10
      this.getTableData(this.selectForm)
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        this.isfooterBtnShow = callbackData.btnType !== 'get'
        if (callbackData.btnType === 'post') {
          this.dialogTitle = '新增'
          if (this.formData.regionIdArr) {
            let arr = this.formData.regionIdArr
            this.formData = {}
            this.formData.regionIdArr = arr
          } else {
            this.formData = {}
          }
        } else {
          this.dialogTitle = callbackData.btnType === 'put' ? '修改' : '查看'
          let obj = {}
          obj = JSON.stringify(callbackData.rows[0])
          this.formData = JSON.parse(obj)
          let regionData = {}
          regionData.id = this.formData.regionId
          regionData.items = this.regionOptions
          this.formData.regionIdArr = getAllRegion(regionData)
          this.level = this.formData.regionIdArr.length
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
      } else {
        this.currentSelectedData = []
      }
    },
    appTreeClick (data) {
      let regionData = {}
      regionData.id = data.id
      regionData.items = this.regionOptions
      this.formData.regionIdArr = getAllRegion(regionData)
      this.selectForm.offset = 0
      this.selectForm.regionId = data.id
      this.getTableData(this.selectForm)
    },
    searchHandleClick () {
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    },
    openSimpleMap () {
      this.mapMode = 'simple'
      this.showMap = true
      this.mapHackReset = true
    },
    appMapCallback (appMapInfo) {
      if (appMapInfo.target) {
        let mapLocation = {}
        mapLocation.targetId = appMapInfo.target.targetId
        mapLocation.targetType = appMapInfo.target.targetType
        if (appMapInfo.clearStatus) {
          mapLocation.clearStatus = appMapInfo.clearStatus
        }
        if (appMapInfo.markPosition) {
          mapLocation.longitude = appMapInfo.markPosition.lng
          mapLocation.latitude = appMapInfo.markPosition.lat
        }
        if (appMapInfo.polyPathArr) {
          mapLocation.mapArea = appMapInfo.polyPathArr
          mapLocation.mapColor = appMapInfo.polyColor
          createMapLocation(mapLocation).then(resp => {
            if (resp.code && resp.code === '200') {
              console.log('保存成功')
            }
          })
        }
      }
      if (appMapInfo.lnglat) {
        this.formData.longitude = appMapInfo.lnglat.lng
        this.formData.latitude = appMapInfo.lnglat.lat
      }
      this.mapCancel()
    },
    mapCancel () {
      this.mapHackReset = false
      this.showMap = false
    }
  }
}
</script>
